package com.proj.hot.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.proj.hot.GlobalParams;
import com.proj.hot.R;
import com.proj.hot.utils.DebugUtil;
import com.proj.hot.utils.TimeService;

import org.json.JSONArray;
import org.json.JSONObject;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * 扫码支付页，里面只有微信和支付宝二维码
 *
 */
public class PayActivity extends BaseActivity {


    TextView pay_price_text;
    ImageView alcode;
//    TextView pyname1,pyname2;

    ListView plistview;
    PayListAdapter payListAdapter;
    JSONArray plist;


    boolean isPay=false;
    boolean isfinish=false;

    private Handler handler =  new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what == 0){

                if(isPay) {
                    Toast.makeText(PayActivity.this, "支付成功！", Toast.LENGTH_LONG).show();
                    handler.removeMessages(0);
                    finish();

                }else{
                    if (!isfinish){
                        getIsPay();
                        handler.sendEmptyMessageDelayed(0,3000);
                    }else{
                        handler.removeMessages(0);
                    }

                }
            }


//            if(msg.what==1){
//
//
//                if(plist.length()>0){
//                    plistview.setItemsCanFocus(true);
//                    plistview.setSelection(0);
//                    plistview.setItemChecked(0,true);
//                }
//            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay);
        plistview=(ListView) findViewById(R.id.plistview);
        pay_price_text=(TextView) findViewById(R.id.pay_price_text);
//        pyname1=(TextView) findViewById(R.id.wxname);
//        pyname2=(TextView) findViewById(R.id.alname);
//        wxcode=(ImageView) findViewById(R.id.wxcode);
        alcode=(ImageView) findViewById(R.id.alcode);
        getpayPic();

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        isfinish=true;
    }

    private void getpayPic(){



        try {



            /**
             * ---------------body------------------
             */

//            {"sn":"设备号","conentid":"购买影片Id","accountid":"用户id"}
            JSONObject body = new JSONObject();
            body.put("sn", GlobalParams.SN);
            body.put("conentid", "");
            body.put("accountid", GlobalParams.user_id);



            RequestParams params = new RequestParams(GlobalParams.reqHost + "attestation/playQRcode");
            params.setAsJsonContent(true);
            params.setBodyContent(body.toString().trim());

            /**
             * ---------------send------------------
             */
            x.http().post(params, new org.xutils.common.Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String s) {
                    try {

                        DebugUtil.i("paytype","包月返回的s="+s);
                        JSONObject jData=new JSONObject(s);

                        JSONObject data=jData.getJSONObject("respbody").getJSONObject("data");

                        plist=data.getJSONArray("paylist");

                        payListAdapter=new PayListAdapter(PayActivity.this,plist);
                        plistview.setAdapter(payListAdapter);



                        plistview.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                try {
                                String pic=plist.getJSONObject(position).getString("payurl");
                                ImageLoader.getInstance().displayImage(pic,alcode);
                                    pay_price_text.setText("￥"+plist.getJSONObject(position).getString("code"));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> parent) {

                            }
                        });


                        if(plist.length()>0){
                            plistview.setSelection(0);
                            String pic=plist.getJSONObject(0).getString("payurl");
                            ImageLoader.getInstance().displayImage(pic,alcode);
                            pay_price_text.setText("￥"+plist.getJSONObject(0).getString("code"));
                        }




                        handler.sendEmptyMessageDelayed(0,3000);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }

                @Override
                public void onFinished() {

                }

                @Override
                public void onCancelled(CancelledException e) {

                }

                @Override
                public void onError(Throwable throwable, boolean b) {

                }
            });


        }catch (Exception e){
            e.printStackTrace();
        }

    }



    private void getIsPay(){

        try {



            /**
             * ---------------body------------------
             */
            JSONObject body = new JSONObject();
//            {"sn":"设备号","conentid":"购买影片Id","accountid":"用户id"}
            body.put("sn", GlobalParams.SN);
            body.put("conentid", "");
            body.put("accountid", GlobalParams.user_id);



            RequestParams params = new RequestParams(GlobalParams.reqHost + "attestation/ispay");
            params.setAsJsonContent(true);
            params.setBodyContent(body.toString().trim());

            /**
             * ---------------send------------------
             */
            x.http().post(params, new org.xutils.common.Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String s) {
                    try {
                        JSONObject jData=new JSONObject(s);

                        JSONObject respbody=jData.getJSONObject("respbody");
                        JSONObject data=respbody.getJSONObject("data");
                        int ltime=data.getInt("duration");
                        if (data.getInt("ispay")==1&&ltime>15*60){
                            isPay=true;

                            GlobalParams.user_paytype="3";

                            GlobalParams.user_Residualduration=ltime;

                            if(!TimeService.TimeServiceIsLive){
                                startService(new Intent(PayActivity.this, TimeService.class));
                            }



                        }


                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }

                @Override
                public void onFinished() {

                }

                @Override
                public void onCancelled(CancelledException e) {

                }

                @Override
                public void onError(Throwable throwable, boolean b) {

                }
            });


        }catch (Exception e){
            e.printStackTrace();
        }

    }















    class PayListAdapter extends BaseAdapter
    {
        private JSONArray arrayList;
        private Context context;

        PayListAdapter(Context context, JSONArray arrayList)
        {
            if (arrayList == null)
            {
                this.arrayList = new JSONArray();
            }
            else
            {
                this.arrayList = arrayList;
            }
            this.context = context;
        }

        @Override
        public int getCount()
        {
            return arrayList.length();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }


        @Override
        public long getItemId(int position)
        {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            ViewHolder holder = null;
            if (convertView == null)
            {
                holder = new ViewHolder();
                convertView = View.inflate(context, R.layout.pay_list_item, null);
                holder.order_name = (TextView) convertView.findViewById(R.id.order_name);

                convertView.setTag(holder);
            }
            else
            {
                holder = (ViewHolder) convertView.getTag();
            }
            try {
                holder.order_name.setText(arrayList.getJSONObject(position).getString("name"));

            }catch (Exception e){
                e.printStackTrace();
            }

            return convertView;
        }

        class ViewHolder
        {
            private TextView order_name;


        }
    }











}
